<template>
  <div class="holders-container">
    <div v-if="isLoading" class="loading">
      <el-icon class="is-loading"><Loading /></el-icon>
      <div>{{ loadingMessage }}</div>
    </div>
    
    <div v-else-if="errorMessage" class="error-message">
      <el-alert
        :title="errorMessage"
        type="error"
        :closable="false"
        show-icon
      />
      <el-button 
        type="primary" 
        @click="retryFetch" 
        style="margin-top: 20px;"
      >
        重试
      </el-button>
    </div>
    
    <div v-else-if="holdersData.length > 0" class="main-content">
      <!-- 左侧持有人列表 -->
      <div class="left-panel">
        <div class="panel-header">
          <h3>持有人列表</h3>
          <span class="total-count">共 {{ totalHolders }} 人</span>
        </div>
        <div class="table-container">
          <el-table 
            :data="currentPageData" 
            stripe 
            highlight-current-row
            @row-click="selectHolder"
            class="holders-table"
          >
            <el-table-column prop="rank" label="排名" width="60" align="center" />
            <el-table-column prop="owner" label="钱包地址" width="180">
              <template #default="scope">
                <div class="address-cell" :class="{ active: selectedHolder?.owner === scope.row.owner }">
                  <span class="address-text">{{ formatAddress(scope.row.owner) }}</span>
                  <el-button 
                    type="text" 
                    size="small" 
                    @click.stop="copyAddress(scope.row.owner)"
                    class="copy-btn"
                  >
                    📋
                  </el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="percentage" label="持仓占比" width="90" align="right">
              <template #default="scope">
                <span class="percentage-text">{{ scope.row.percentage?.toFixed(2) || 'N/A' }}%</span>
              </template>
            </el-table-column>
            <el-table-column prop="profit" label="利润" width="90" align="right">
              <template #default="scope">
                <span :class="(scope.row.profit || 0) >= 0 ? 'profit-positive' : 'profit-negative'">
                  ${{ formatNumber(scope.row.profit || 0) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="profit_rate" label="利润率" width="90" align="right">
              <template #default="scope">
                <span :class="(scope.row.profit_rate || 0) >= 0 ? 'profit-positive' : 'profit-negative'">
                  {{ (scope.row.profit_rate || 0).toFixed(2) }}%
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="trade_type" label="买/卖" width="70" align="center">
              <template #default="scope">
                <span :class="scope.row.trade_type === 'buy' ? 'trade-buy' : 'trade-sell'">
                  {{ scope.row.trade_type === 'buy' ? '买' : '卖' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="is_internal" label="内/外" width="70" align="center">
              <template #default="scope">
                <span :class="scope.row.is_internal ? 'internal-trade' : 'external-trade'">
                  {{ scope.row.is_internal ? '内' : '外' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="source" label="资金来源" width="90" align="center">
              <template #default="scope">
                {{ scope.row.source || '未知' }}
              </template>
            </el-table-column>
            <el-table-column prop="transfer_time" label="转账时间" width="100" align="center">
              <template #default="scope">
                {{ formatTime(scope.row.transfer_time) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        
      </div>
      
      <!-- 右侧相同代币持有人区域 -->
      <div class="right-panel">
        <div class="panel-header">
          <h3>持有人相同代币</h3>
        </div>
        
        <div v-if="sameTokenHoldersLoading" class="loading">
          <div class="loading-content">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>正在分析持有人投资组合...</span>
          </div>
          <div class="progress-info">
            <el-progress :percentage="analysisProgress" :show-text="true" />
            <el-button 
              type="danger" 
              size="small" 
              @click="cancelAnalysis"
              class="cancel-btn"
            >
              取消分析
            </el-button>
          </div>
        </div>
        
        <div v-else-if="sameTokenHoldersError" class="error-message">
          <el-alert
            :title="sameTokenHoldersError"
            type="error"
            :closable="false"
            show-icon
          />
        </div>
        
        <div v-else-if="sameTokenHoldersData.length > 0" class="same-token-content">
          <el-table :data="sameTokenHoldersData" stripe class="same-token-table">
            <el-table-column prop="token_symbol" label="代币">
              <template #default="scope">
                <div class="token-info">
                  <img 
                    v-if="scope.row.token_icon" 
                    :src="scope.row.token_icon" 
                    :alt="scope.row.token_symbol"
                    class="token-icon"
                    @error="handleImageError"
                  />
                  <span class="token-symbol">{{ scope.row.token_symbol }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="holder_count" label="人数" width="100" align="center">
              <template #default="scope">
                <span class="holder-count">{{ scope.row.holder_count }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template #default="scope">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="showFilterDialog(scope.row)"
                >
                  筛选
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <div v-else class="empty-portfolio">
          <el-empty description="暂无相同代币数据" />
        </div>
      </div>
      
      <!-- 右侧第二个表格：资金来源相同代币 -->
      <div class="right-panel second-panel">
        <div class="panel-header">
          <h3>资金来源相同代币</h3>
        </div>
        
        <div v-if="sourceTokenHoldersLoading" class="loading">
          <div class="loading-content">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>正在分析资金来源...</span>
          </div>
        </div>
        
        <div v-else-if="sourceTokenHoldersError" class="error-message">
          <el-alert
            :title="sourceTokenHoldersError"
            type="error"
            :closable="false"
            show-icon
          />
        </div>
        
        <div v-else-if="sourceTokenHoldersData.length > 0" class="source-token-content">
          <el-table :data="sourceTokenHoldersData" stripe class="source-token-table">
            <el-table-column prop="token_symbol" label="代币" width="120">
              <template #default="scope">
                <div class="token-info">
                  <img 
                    v-if="scope.row.token_icon" 
                    :src="scope.row.token_icon" 
                    :alt="scope.row.token_symbol"
                    class="token-icon"
                    @error="handleImageError"
                  />
                  <span class="token-symbol">{{ scope.row.token_symbol }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="holder_count" label="人数" width="80" align="center">
              <template #default="scope">
                <span class="holder-count">{{ scope.row.holder_count }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" align="center">
              <template #default="scope">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="showSourceFilterDialog(scope.row)"
                >
                  筛选
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <div v-else class="empty-portfolio">
          <el-empty description="暂无资金来源数据" />
        </div>
      </div>
    </div>
    
    <div v-else class="empty-data">
      <el-empty description="暂无持有人数据" />
    </div>
    
    <!-- 持仓详情弹窗 -->
    <el-dialog
      v-model="portfolioVisible"
      :title="`${formatAddress(selectedHolder?.owner || '')} 的持仓详情`"
      width="60%"
      :before-close="handleClosePortfolio"
      class="portfolio-dialog"
    >
      <div v-if="portfolioLoading" class="loading">
        <el-icon class="is-loading"><Loading /></el-icon>
        正在查询持仓数据...
      </div>
      
      <div v-else-if="portfolioError" class="error-message">
        <el-alert
          :title="portfolioError"
          type="error"
          :closable="false"
          show-icon
        />
      </div>
      
      <div v-else-if="portfolioData" class="portfolio-content">
        <!-- 总价值概览 -->
        <div class="total-value">
          <div class="value-item">
            <span class="label">总价值:</span>
            <span class="value">${{ formatNumber(portfolioData.total_value) }}</span>
          </div>
          <div class="value-item">
            <span class="label">SOL余额:</span>
            <span class="value">{{ formatNumber(portfolioData.native_balance?.balance) }} SOL</span>
          </div>
          <div class="value-item">
            <span class="label">SOL价值:</span>
            <span class="value">${{ formatNumber(portfolioData.native_balance?.value) }}</span>
          </div>
        </div>
        
        <!-- 代币持仓列表 -->
        <div class="tokens-section">
          <h4>代币持仓 ({{ portfolioData.tokens?.length || 0 }} 个代币)</h4>
          <el-table :data="portfolioData.tokens" stripe class="tokens-table">
            <el-table-column prop="token_symbol" label="代币" >
              <template #default="scope">
                <div class="token-info">
                  <img 
                    v-if="scope.row.token_icon" 
                    :src="scope.row.token_icon" 
                    :alt="scope.row.token_symbol"
                    class="token-icon"
                    @error="handleImageError"
                  />
                  <span class="token-symbol">{{ scope.row.token_symbol }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="token_name" label="名称" />
            <el-table-column prop="balance" label="数量" align="right">
              <template #default="scope">
                {{ formatNumber(scope.row.balance) }}
              </template>
            </el-table-column>
            <el-table-column prop="token_price" label="单价" align="right">
              <template #default="scope">
                ${{ formatNumber(scope.row.token_price) }}
              </template>
            </el-table-column>
            <el-table-column prop="value" label="价值" align="right">
              <template #default="scope">
                <span class="value-text">${{ formatNumber(scope.row.value) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="占比" align="right">
              <template #default="scope">
                <span class="percentage-text">
                  {{ calculatePercentage(scope.row.value, portfolioData.total_value) }}%
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
    
    <!-- 筛选弹框 -->
    <el-dialog
      v-model="filterDialogVisible"
      :title="`${selectedSameToken?.token_symbol} 持有人列表`"
      width="60%"
      :before-close="handleCloseFilterDialog"
      class="filter-dialog"
    >
      <div v-if="filterLoading" class="loading">
        <el-icon class="is-loading"><Loading /></el-icon>
        正在查询持有人列表...
      </div>
      
      <div v-else-if="filterError" class="error-message">
        <el-alert
          :title="filterError"
          type="error"
          :closable="false"
          show-icon
        />
      </div>
      
      <div v-else-if="filterHoldersData.length > 0" class="filter-content">
        <div class="filter-summary">
          <span>共找到 {{ filterHoldersData.length }} 个持有人</span>
        </div>
        
        <el-table :data="filterHoldersData" stripe class="filter-table" max-height="400">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="address" label="钱包地址" min-width="200">
            <template #default="scope">
              <div class="address-cell">
                <span class="address-text">{{ formatAddress(scope.row.address) }}</span>
                <el-button 
                  type="text" 
                  size="small" 
                  @click="copyAddress(scope.row.address)"
                  class="copy-btn"
                >
                  复制
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="balance" label="持仓量" width="120" align="right">
            <template #default="scope">
              {{ formatNumber(scope.row.balance) }}
            </template>
          </el-table-column>
          <el-table-column prop="percentage" label="占比" width="100" align="right">
            <template #default="scope">
              {{ scope.row.percentage }}%
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div v-else class="empty-filter">
        <el-empty description="暂无持有人数据" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { Loading } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { tokenAPI } from '../utils/api.js'

// Props
const props = defineProps({
  contractAddress: String,
  isLoading: Boolean
})

// Emits
const emit = defineEmits(['loading-change'])

// Reactive data
const holdersData = ref([])
const totalHolders = ref(0)
const selectedHolder = ref(null)
const portfolioLoading = ref(false)
const portfolioData = ref(null)
const portfolioError = ref('')
const errorMessage = ref('')
const loadingMessage = ref('正在查询持有人数据...')
const portfolioVisible = ref(false)

// 相同代币持有人相关数据
const sameTokenHoldersData = ref([])
const sameTokenHoldersLoading = ref(false)
const sameTokenHoldersError = ref('')
const analysisProgress = ref(0)
const analysisCanceled = ref(false)

// 筛选弹框相关数据
const filterDialogVisible = ref(false)
const selectedSameToken = ref(null)
const filterHoldersData = ref([])
const filterLoading = ref(false)
const filterError = ref('')

// 资金来源相同代币相关数据
const sourceTokenHoldersData = ref([])
const sourceTokenHoldersLoading = ref(false)
const sourceTokenHoldersError = ref('')

// Computed
const currentPageData = computed(() => {
  return holdersData.value
})

// Methods
const fetchHolders = async () => {
  emit('loading-change', true)
  holdersData.value = []
  errorMessage.value = ''
  selectedHolder.value = null
  portfolioData.value = null
  
  try {
    // 使用新API一次获取100个持有人
    loadingMessage.value = '正在获取持有人数据...'
    console.log('正在获取持有人数据...')
    const data = await tokenAPI.getHolders(props.contractAddress, 1, 100)
    
    if (data.success && data.data && data.data.items) {
      // 只取前50个
      holdersData.value = data.data.items.slice(0, 50)
      totalHolders.value = Math.min(data.data.items.length, 50)
    } else {
      throw new Error('API返回数据格式错误')
    }
    
    loadingMessage.value = `数据获取完成，共${holdersData.value.length}个持有人`
    console.log(`成功获取${holdersData.value.length}个持有人数据`)
    
    // 先结束持有人数据的loading状态，让持有人列表先显示
    emit('loading-change', false)
    
    // 异步获取相同代币持有人数据（不阻塞持有人列表显示）
    fetchSameTokenHolders()
    // 异步获取资金来源相同代币数据
    fetchSourceTokenHolders()
  } catch (error) {
    console.error('获取持有人数据失败:', error)
    errorMessage.value = `查询失败：${error.response?.data?.message || error.message || '网络错误，请稍后重试'}`
    emit('loading-change', false)
  }
}

const fetchSameTokenHolders = async () => {
  sameTokenHoldersLoading.value = true
  sameTokenHoldersError.value = ''
  sameTokenHoldersData.value = []
  analysisProgress.value = 0
  analysisCanceled.value = false

  try {
    // 获取前50个持有人的投资组合数据进行分析
    const holdersToAnalyze = holdersData.value.slice(0, 50)
    const tokenStats = new Map() // 用于统计代币持有情况
    
    // 分批并发请求，每批5个
    const batchSize = 5
    const batches = []
    
    for (let i = 0; i < holdersToAnalyze.length; i += batchSize) {
      batches.push(holdersToAnalyze.slice(i, i + batchSize))
    }
    
    let completedBatches = 0
    
    for (const batch of batches) {
      // 检查是否取消
      if (analysisCanceled.value) {
        console.log('分析已取消')
        break
      }
      
      // 并发请求当前批次的所有持有人投资组合
      const promises = batch.map(async (holder) => {
        try {
          const data = await tokenAPI.getPortfolio(holder.owner)
          if (data.success && data.data && data.data.tokens) {
            return {
              holder: holder.owner,
              tokens: data.data.tokens
            }
          }
          return null
        } catch (error) {
          console.warn(`获取持有人 ${holder.owner} 的投资组合失败:`, error)
          return null
        }
      })
      
      const results = await Promise.all(promises)
      
      // 统计代币持有情况
      results.forEach(result => {
        if (result && result.tokens) {
          result.tokens.forEach(token => {
            const key = token.token_address || token.token_symbol
            if (key) {
              if (!tokenStats.has(key)) {
                tokenStats.set(key, {
                  token_symbol: token.token_symbol,
                  token_name: token.token_name,
                  token_icon: token.token_icon,
                  token_address: token.token_address,
                  holder_count: 0,
                  holders: []
                })
              }
              const tokenInfo = tokenStats.get(key)
              tokenInfo.holder_count++
              tokenInfo.holders.push({
                address: result.holder,
                balance: token.balance,
                value: token.value
              })
            }
          })
        }
      })
      
      completedBatches++
      // 更新进度
      const progress = Math.round((completedBatches / batches.length) * 100)
      analysisProgress.value = progress
      console.log(`分析进度: ${progress}% (${completedBatches}/${batches.length} 批次完成)`)
      
      // 添加延迟避免API限制
      if (completedBatches < batches.length && !analysisCanceled.value) {
        await new Promise(resolve => setTimeout(resolve, 1000))
      }
    }
    
    if (!analysisCanceled.value) {
      // 转换为数组并按持有人数量排序
      const sortedTokens = Array.from(tokenStats.values())
        .filter(token => token.holder_count > 1) // 只显示有多个持有人的代币
        .sort((a, b) => b.holder_count - a.holder_count)
        .slice(0, 50) // 只显示前50个
      
      sameTokenHoldersData.value = sortedTokens
      console.log(`分析完成，找到 ${sortedTokens.length} 个共同持有的代币`)
    }
    
  } catch (error) {
    console.error('获取相同代币持有人失败:', error)
    sameTokenHoldersError.value = `获取相同代币持有人失败：${error.response?.data?.message || error.message || '网络错误'}`
  } finally {
    sameTokenHoldersLoading.value = false
    analysisProgress.value = 0
  }
}

const cancelAnalysis = () => {
  analysisCanceled.value = true
  sameTokenHoldersLoading.value = false
  console.log('用户取消了分析')
}

const fetchSourceTokenHolders = async () => {
  sourceTokenHoldersLoading.value = true
  sourceTokenHoldersError.value = ''
  sourceTokenHoldersData.value = []

  try {
    // 模拟资金来源相同代币数据
    const mockSourceData = [
      // { token_symbol: 'Fartcoin', token_icon: '', holder_count: 15 },
      // { token_symbol: 'LAUNCHCOIN', token_icon: '', holder_count: 10 },
      // { token_symbol: 'LIBRA', token_icon: '', holder_count: 8 },
      // { token_symbol: 'TRUMP', token_icon: '', holder_count: 7 },
      // { token_symbol: 'GOONC', token_icon: '', holder_count: 6 },
      // { token_symbol: 'DUPE', token_icon: '', holder_count: 5 },
      // { token_symbol: 'gork', token_icon: '', holder_count: 4 },
      // { token_symbol: 'House', token_icon: '', holder_count: 3 }
    ]
    
    sourceTokenHoldersData.value = mockSourceData
  } catch (error) {
    console.error('获取资金来源相同代币失败:', error)
    sourceTokenHoldersError.value = `获取资金来源相同代币失败：${error.response?.data?.message || error.message || '网络错误'}`
  } finally {
    sourceTokenHoldersLoading.value = false
  }
}

const showSourceFilterDialog = async (sourceToken) => {
  selectedSameToken.value = sourceToken
  filterDialogVisible.value = true
  filterLoading.value = true
  filterHoldersData.value = []
  filterError.value = ''

  try {
    // 模拟资金来源筛选数据
    const mockSourceHoldersData = [
      // { address: 'Source1...abc123', balance: 5000000, percentage: 15.5 },
      // { address: 'Source2...def456', balance: 3200000, percentage: 12.3 },
      // { address: 'Source3...ghi789', balance: 2800000, percentage: 10.8 },
      // { address: 'Source4...jkl012', balance: 2100000, percentage: 8.2 },
      // { address: 'Source5...mno345', balance: 1800000, percentage: 7.1 }
    ]
    
    filterHoldersData.value = mockSourceHoldersData
  } catch (error) {
    console.error('获取资金来源筛选失败:', error)
    filterError.value = `获取资金来源筛选失败：${error.response?.data?.message || error.message || '网络错误'}`
  } finally {
    filterLoading.value = false
  }
}

const selectHolder = async (holder) => {
  selectedHolder.value = holder
  portfolioVisible.value = true
  portfolioLoading.value = true
  portfolioData.value = null
  portfolioError.value = ''
  
  try {
    const data = await tokenAPI.getPortfolio(holder.owner)
    
    if (data.success && data.data) {
      portfolioData.value = data.data
    } else {
      throw new Error('API返回数据格式错误')
    }
  } catch (error) {
    console.error('获取投资组合失败:', error)
    portfolioError.value = `获取投资组合失败：${error.response?.data?.message || error.message || '网络错误'}`
  } finally {
    portfolioLoading.value = false
  }
}


const retryFetch = () => {
  fetchHolders()
}

const handleClosePortfolio = () => {
  portfolioVisible.value = false
  selectedHolder.value = null
  portfolioData.value = null
  portfolioError.value = ''
}

const handleImageError = (event) => {
  event.target.style.display = 'none'
}

const calculatePercentage = (value, total) => {
  if (!value || !total || total === 0) return '0.00'
  const percentage = (value / total) * 100
  return percentage.toFixed(2)
}

const showFilterDialog = async (sameToken) => {
  selectedSameToken.value = sameToken
  filterDialogVisible.value = true
  filterLoading.value = true
  filterHoldersData.value = []
  filterError.value = ''

  try {
    // 使用已统计的持有人数据
    if (sameToken.holders && sameToken.holders.length > 0) {
      // 总数是10亿，m = 100万
      // 10m = 1%, 1m = 0.1%, 500k = 0.05%
      const totalSupply = 1000000000 // 10亿
      
      const holdersData = sameToken.holders.map(holder => {
        const balance = holder.balance || 0
        // 计算百分比：balance / 10亿 * 100
        const percentage = (balance / totalSupply * 100).toFixed(2)
        
        return {
          address: holder.address,
          balance: balance,
          percentage: percentage
        }
      })
      
      filterHoldersData.value = holdersData
    } else {
      filterHoldersData.value = []
    }
  } catch (error) {
    console.error('获取筛选持有人失败:', error)
    filterError.value = `获取持有人列表失败：${error.response?.data?.message || error.message || '网络错误'}`
  } finally {
    filterLoading.value = false
  }
}

const handleCloseFilterDialog = () => {
  filterDialogVisible.value = false
  selectedSameToken.value = null
  filterHoldersData.value = []
  filterError.value = ''
}

const copyAddress = async (address) => {
  try {
    await navigator.clipboard.writeText(address)
    ElMessage.success('地址已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败，请手动复制')
  }
}

const formatAddress = (address) => {
  if (!address) return 'N/A'
  return address.length > 20 ? 
    address.substring(0, 8) + '...' + address.substring(address.length - 8) : 
    address
}

const formatNumber = (num) => {
  if (num === null || num === undefined) return 'N/A'
  if (typeof num === 'string') num = parseFloat(num)
  if (isNaN(num)) return 'N/A'
  
  if (num >= 1e9) {
    return (num / 1e9).toFixed(2) + 'B'
  } else if (num >= 1e6) {
    return (num / 1e6).toFixed(2) + 'M'
  } else if (num >= 1e3) {
    return (num / 1e3).toFixed(2) + 'K'
  } else {
    return num.toFixed(2)
  }
}

const formatTime = (timestamp) => {
  if (!timestamp) return 'N/A'
  const date = new Date(timestamp * 1000)
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// Watchers
watch(() => props.contractAddress, (newAddress) => {
  if (newAddress) {
    fetchHolders()
  }
}, { immediate: true })
</script>

<style scoped>
.holders-container {
  padding: 20px;
  margin-top: 20px;
}

.main-content {
  display: flex;
  gap: 20px;
  height: calc(100vh - 200px);
  max-height: 800px;
}

.left-panel {
  flex: 2;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.right-panel {
  flex: 1;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.second-panel {
  margin-bottom: 0;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.total-count {
  color: #909399;
  font-size: 14px;
}

/* 表格容器样式 */
.table-container {
  flex: 1;
  overflow: auto;
  min-height: 0;
}

.holders-table {
  width: 100%;
}

/* 确保表格在容器内正确显示 */
.holders-table :deep(.el-table__body-wrapper) {
  max-height: 500px !important;
  overflow-y: auto !important;
}

.address-cell {
  font-family: 'Courier New', monospace;
  font-size: 12px;
  cursor: pointer;
}

.address-cell.active {
  background: #409eff;
  color: white;
}

.amount-text {
  font-weight: 600;
  color: #67c23a;
}

.percentage-text {
  color: #909399;
}


.empty-portfolio {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
}

.loading {
  text-align: center;
  padding: 40px;
}

.error-message {
  text-align: center;
  padding: 20px;
}

.portfolio-content {
  padding: 20px 0;
}

.total-value {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.value-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.value-item:last-child {
  margin-bottom: 0;
}

.tokens-section h4 {
  margin: 0 0 15px 0;
  font-size: 16px;
}

.tokens-table {
  margin-top: 15px;
}

.token-info {
  display: flex;
  align-items: center;
  gap: 6px;
}

.token-icon {
  width: 20px;
  height: 20px;
  border-radius: 50%;
}

.token-symbol {
  font-weight: 600;
}

.value-text {
  font-weight: 600;
  color: #67c23a;
}

.empty-data {
  text-align: center;
  padding: 40px;
  color: #909399;
}


/* 相同代币持有人表格样式 */
.same-token-table {
  margin-top: 15px;
  flex: 1;
  overflow: auto;
  min-height: 0;
}

.same-token-table :deep(.el-table__body-wrapper) {
  max-height: 300px !important;
  overflow-y: auto !important;
}

/* 进度显示样式 */
.loading-content {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.progress-info {
  display: flex;
  flex-direction: column;
  gap: 10px;
  align-items: center;
}

.same-token-table .token-info {
  display: flex;
  align-items: center;
  gap: 6px;
}

.same-token-table .token-icon {
  width: 20px;
  height: 20px;
  border-radius: 50%;
}

.same-token-table .token-symbol {
  font-weight: 600;
  font-size: 12px;
}

.same-token-table .holder-count {
  font-weight: 600;
  color: #409eff;
  font-size: 12px;
}

/* 筛选弹框样式 */
.filter-content {
  padding: 0;
}

.filter-summary {
  margin-bottom: 15px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.filter-table {
  margin-top: 15px;
}

.filter-table .address-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
}

.filter-table .address-text {
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.empty-filter {
  text-align: center;
  padding: 40px;
  color: #909399;
}

/* 状态样式 */
.profit-positive {
  color: #67c23a;
  font-weight: 600;
}

.profit-negative {
  color: #f56c6c;
  font-weight: 600;
}

.trade-buy {
  color: #67c23a;
  font-weight: 600;
}

.trade-sell {
  color: #f56c6c;
  font-weight: 600;
}

.internal-trade {
  color: #409eff;
  font-weight: 600;
}

.external-trade {
  color: #909399;
  font-weight: 600;
}

.address-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
}

.address-text {
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.copy-btn {
  padding: 1px 4px;
  font-size: 12px;
  min-width: auto;
}

/* 资金来源表格样式 */
.source-token-table {
  margin-top: 15px;
  flex: 1;
  overflow: auto;
  min-height: 0;
}

.source-token-table :deep(.el-table__body-wrapper) {
  max-height: 300px !important;
  overflow-y: auto !important;
}

.source-token-table .token-info {
  display: flex;
  align-items: center;
  gap: 6px;
}

.source-token-table .token-icon {
  width: 20px;
  height: 20px;
  border-radius: 50%;
}

.source-token-table .token-symbol {
  font-weight: 600;
  font-size: 12px;
}

.source-token-table .holder-count {
  font-weight: 600;
  color: #e6a23c;
  font-size: 12px;
}

@media (max-width: 1200px) {
  .main-content {
    flex-direction: column;
    gap: 15px;
    height: auto;
    max-height: none;
  }
  
  .left-panel {
    flex: none;
    width: 100%;
    height: 500px;
  }
  
  .right-panel {
    flex: none;
    width: 100%;
    margin-bottom: 15px;
    height: 300px;
  }
  
  .second-panel {
    margin-bottom: 0;
    height: 300px;
  }
  
  .table-container {
    overflow-x: auto;
  }
  
  .holders-table {
    min-width: 800px;
  }
  
  .panel-header {
    flex-direction: column;
    gap: 10px;
    text-align: center;
  }
}

@media (max-width: 768px) {
  .holders-table {
    min-width: 700px;
  }
}
</style>
